﻿@rendermode InteractiveServer
@using Microsoft.FluentUI.AspNetCore.Components
@using Microsoft.FluentUI.AspNetCore.Components.DesignTokens
@using Icon = Microsoft.FluentUI.AspNetCore.Components.Icon
@using Icons = Microsoft.FluentUI.AspNetCore.Components.Icons
@using Color = Microsoft.FluentUI.AspNetCore.Components.Color

@inject AccentBaseColor AccentBaseColor

<FluentStack HorizontalGap="2" class="toolbar">

	@foreach (var btn in BtnLst)
	{
		<FluentButton Appearance="Appearance.Neutral"
					  IconStart="@btn.icon"
					  OnClick="(e) => ButtonClick(e, btn.name)">
			@btn.name
		</FluentButton>
	}

	<FluentMenuButton @ref=menubutton Text="@BtnNameConsts.Set"
					  Items="@BtnSetItems" ButtonAppearance="Appearance.Neutral"
					  IconStart="new Icons.Regular.Size24.Settings()"
					  OnMenuChanged="HandleOnMenuChanged">
	</FluentMenuButton>
</FluentStack>

<style>
	.toolbar {
		border: 1px groove;
		padding: 2px;
		height: 36px;
	}
</style>

@code {
	#region Parameter

	[Parameter]
	public EventCallback<ToolEventArgs> OnToolClick { get; set; }

	[Parameter]
	public List<(string name, Icon icon)> BtnLst { get; set; }

	[Parameter]
	public Dictionary<string, string> BtnSetItems { get; set; }

	#endregion


	private FluentMenuButton menubutton = new();

	protected override async Task OnInitializedAsync()
	{
		InitToolBar();
		await base.OnInitializedAsync();
	}

	protected void InitToolBar()
	{
		if (!BtnLst.HasItem())
		{
			BtnLst = new List<(string, Icon)>()
			{
				(BtnNameConsts.Add,new Icons.Regular.Size24.Add()),
				(BtnNameConsts.Edit,new Icons.Regular.Size24.Edit()),
				(BtnNameConsts.Save,new Icons.Regular.Size24.Save().WithColor(Color.Success)),
				(BtnNameConsts.Delete,new Icons.Regular.Size24.DismissCircle().WithColor("red")),
				//(BtnNameConsts.Audit,new Icons.Regular.Size24.Alert().WithColor(Color.Warning))
			};
		}

		if (!BtnSetItems.HasItem())
		{
			BtnSetItems = new Dictionary<string, string>()
			{
				{"0078D4",BtnNameConsts.Params},
				{"0022CC",BtnNameConsts.BtnParams},
				{"464EB8",BtnNameConsts.DataSource},
			};
		}

	}

	private async Task HandleOnMenuChanged(MenuChangeEventArgs args)
	{
		await AccentBaseColor.SetValueFor(menubutton.Button!.Element, $"#{args.Id}".ToSwatch());

		var toolArgs = new ToolEventArgs()
		{
			ButtonName = args.Value,
			EventArgs = args
		};
		await OnToolClickHandlerAsync(toolArgs);
	}


	protected async Task OnToolClickHandlerAsync(ToolEventArgs e)
	{
		if (OnToolClick.HasDelegate)
		{
			await OnToolClick.InvokeAsync(e);
		}

		await Task.CompletedTask;
	}

	public async Task ButtonClick(MouseEventArgs args, string buttonName)
	{
		var toolArgs = new ToolEventArgs()
		{
			ButtonName = buttonName,
			EventArgs = args
		};
		await OnToolClickHandlerAsync(toolArgs);
	}
}